<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        // 浅拷贝：针对于引用数据类型的数据进行赋值的一种操作概念，只针对于数组或者对象的第一层数据进行赋值操作
        // 1.循环赋值
        var arr = ["alice", "baby", ["a", "b", "c"]];
        var user = { name: "tom", age: 20, skills: ["唱歌", "跳舞", "rap"] };
        // a.循环浅拷贝
        // function copy(obj){
        //     let arrs=[];
        //     for(let i in obj){
        //         arrs[i]=obj[i];//arrs[0]=arr[0]  arrs[1]=arr[1]  arrs[2]=arr[2]
        //     }
        //     return arrs;
        // }
        // let ar=copy(arr);
        // arr[2][0]="群魔乱舞";
        // console.log2(ar);
        function copy2(obj) {

            let objs = {};
            for (let i in obj) {
                console.log(i);
                objs[i] = obj[i];//objs["name"]=user["name"]  objs["age"]=user["age"]  objs["skills"]=user["skills"]
            }
            return objs;
        }
        let u = copy2(user);
        user.skills[0] = "弹琴";
        console.log(u);

        // b.解构赋值的浅拷贝
        // let [...arrays]=arr;
        // arrays[2][1]="嘻嘻"
        // console.log(arr);
        // c.展开运算符的浅拷贝
        let arr2 = [...arr];
        let user2 = { ...user };
        arr2[2][2] = "hello";
        user2["skills"][2] = "world";
        console.log(arr);
        console.log(user);

        // 2.深拷贝：针对于引用数据类型的数据进行赋值的一种操作概念，只针对于数组或者对象的每一层数据进行赋值操作
        // a.JSON工具包(JSON工具包内置方法本身自带深度循环)
        var newArr = ["alice", "baby", ["a", "b", "c"]];
        var str = JSON.stringify(newArr);
        console.log(str);
        var newArrs = JSON.parse(str);
        newArrs[2][0] = "嘻嘻嘻嘻嘻";
        console.log(newArrs);
        console.log(newArr);

        // b.递归拷贝
        // 递归：一个函数在执行的时候，函数调用了函数本身，递归函数中必须存在一个明确的逻辑判断
        let users = {
            name: "罗志祥",
            skill: "时间管理大师",
            addr: {
                city: "台湾"
            }
        };

        function deepCopy(obj1, obj2) {
            for (let key in obj2) {   // in obj2["addr"]
                if (typeof obj2[key] == "object") {//obj2["addr"]["city"]
                    obj1[key]={};
                    deepCopy(obj1[key],obj2[key]);//deepCopy(obj1["addr"],obj2["addr"])
                } else {
                    obj1[key] = obj2[key];//obj1["addr"]["city"]="台湾"
                }
            }
        }

        let userOne = {};
        deepCopy(userOne, users);
        userOne.addr.city="上海";
        console.log(users);
        console.log(userOne);



    </script>
</head>

<body>

</body>

</html>